using System.Collections.Generic;
using System.ComponentModel;
using DictToObject.Helpers;

namespace DictToObject.FieldExpectations
{
    public class OptionalFieldExpectation : IOptionalFieldExpectation
    {
        private readonly string key;
        private readonly IFieldLikeMember member;
        private readonly object defaultValue;

        public OptionalFieldExpectation(string key, IFieldLikeMember member, object defaultValue)
        {
            this.key = key;
            this.member = member;
            this.defaultValue = defaultValue;
        }

        public void Apply(object result, IDictionary<string, string> values)
        {
            string value;
            if (!values.TryGetValue(key, out value))
                member.SetValue(result, defaultValue);
            else
                member.SetValue(result, ConvertValue(value));
        }

        private object ConvertValue(string value)
        {
            return member.Type == typeof(string) ? value : TypeDescriptor.GetConverter(member.Type).ConvertFrom(value);
        }
    }
}